from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

from common.utils import forum_driver


class SignInTest():
    driver = ""
    url = ""

    def __init__(self):
        self.driver = forum_driver.driver
        self.url = "http://127.0.0.1:58080/sign-in.html"
        print(f"访问网址: {self.url}")
        self.driver.get(self.url)

    #封装显示等待
    def wait_for_element(self, by, locator, timeout=5):
        return WebDriverWait(self.driver, timeout).until(
            EC.visibility_of_element_located((by, locator))
        )

    def input_clear(self):
        self.wait_for_element(By.XPATH, "//*[@id=\"username\"]").clear()
        self.wait_for_element(By.XPATH, "//*[@id=\"password\"]").clear()

    def signin_suc_test(self):
        self.input_clear()
        self.wait_for_element(By.XPATH, "//*[@id=\"username\"]").send_keys("lisi")
        self.wait_for_element(By.XPATH, "//*[@id=\"password\"]").send_keys("123456")
        self.wait_for_element(By.XPATH, "//*[@id=\"submit\"]").click()
        WebDriverWait(self.driver, 5).until(
            lambda driver: driver.current_url != self.url
        )
        assert "index.html" in self.driver.current_url
        forum_driver.get_screenshot()


    def signin_fail_test(self):
        self.input_clear()
        self.wait_for_element(By.XPATH, "//*[@id=\"username\"]").send_keys("notexist")
        self.wait_for_element(By.XPATH, "//*[@id=\"submit\"]").click()
        text = self.wait_for_element(By.XPATH, "//*[@id=\"signInForm\"]/div[2]/div/div").text
        assert text == "密码不能为空","密码不为空校验失败"
        forum_driver.get_screenshot()
        self.wait_for_element(By.XPATH, "//*[@id=\"password\"]").send_keys("notexist")
        self.wait_for_element(By.XPATH, "//*[@id=\"submit\"]").click()
        text = self.wait_for_element(By.CSS_SELECTOR, "body > div.jq-toast-wrap.bottom-right > div").text
        assert "用户名或密码错误" in text, "用户名和密码错误校验失败"
        forum_driver.get_screenshot()

    #跳转注册再返回
    def signin_to_signup(self):
        self.wait_for_element(By.XPATH, "/html/body/div[1]/div/div/div[1]/div/div[3]/a").click()
        forum_driver.get_screenshot()
        self.driver.back()
        self.driver.refresh()


# signin = SignInTest()
# signin.signin_fail_test()
# signin.signin_to_signup()
# signin.signin_suc_test()

